import WebGl from '@/modules/three';
// import fontJson from 'three/examples/fonts/helvetiker_regular.typeface.json'
const fontJson = require('three/examples/fonts/helvetiker_regular.typeface.json');

const { Three, TWEEN, dat, Stats } = WebGl;

class WebGlControl {
  private container: any;
  private camera: any;
  private scene: any;
  private renderer: any;
  private stats: any;
  private loader: any;
  private tween: any;
  private animateFrame: any;
  private particleSystem: any; //

  private Geometrys: {
    cubeGeometry?: any;
    starsGeometry?: any;
  } = {}; //保存所有Geometry，方便统一销毁
  private Materials: {
    cubeMaterial?: any;
    starsMaterial?: any;
  } = {}; //保存所有Material，方便统一销毁

  private GuiInit: any = null;
  private guiData: any = {
    color: '#ffffff',
    mouseMove: false,
    autoRotate: true,
    SEPARATION: 100,
    AMOUNTX: 50,
    AMOUNTY: 50,
    positionYBase: 50, //粒子y晃动幅度
  };
  private mouseData: any = {
    mouseX: 0,
    mouseY: 0,
  };

  public init = () => {
    // if(this.scene) {return}
    this.container = document.getElementById('WebGL-points-cpu');
    let width = this.container.clientWidth,
      height = this.container.clientHeight;

    this.scene = new Three.Scene();

    this.camera = new Three.PerspectiveCamera(40, width / height, 1, 10000);
    this.camera.position.z = 150;
    this.camera.lookAt(this.scene.position);

    this.renderer = new Three.WebGLRenderer();
    // this.renderer.setClearColor( 0xffffff );
    this.renderer.setPixelRatio(window.devicePixelRatio);
    this.renderer.setSize(width, height);
    this.container.appendChild(this.renderer.domElement);

    this.loader = new Three.ObjectLoader(); //JSONLoader 已经移除了

    this.addThings();
    this.addLight(); //+光源
    this.animate(); //开始动
    this.initEventListen();
    this.initStats();

    this.initGui();
  };
  public destroy = () => {
    this.toggleGui(0);
    Object.values(this.Geometrys).forEach((e) => {
      e.dispose();
    });
    Object.values(this.Materials).forEach((e) => {
      e.dispose();
    });
    this.scene.clear();
    this.renderer.dispose();
    this.renderer.forceContextLoss();
    this.camera = null;
    this.scene = null;
    this.renderer = null;
    this.GuiInit = null;
    cancelAnimationFrame(this.animateFrame);

    this.tween.stop();
    this.tween = null;
  };

  public initGui = () => {
    if (this.GuiInit) {
      this.toggleGui();
      return;
    }
    this.GuiInit = new dat.GUI({
      // autoPlace: false
    });

    this.GuiInit.domElement.style.position = 'absolute';
    this.GuiInit.domElement.style.right = '10px';
    this.GuiInit.domElement.style.top = '10px';

    let GuiController = this.GuiInit.addFolder('控制窗口');
    // GuiController.addColor(this.guiData, "color").name('粒子颜色');
    // GuiController.add(this.guiData, "mouseMove").name('鼠标晃动');
    GuiController.open();

    // let starsGui = this.GuiInit.addFolder("stars position");
    // starsGui.add(this.particleSystem.position, 'x', -500, 500, 1);
    // starsGui.add(this.particleSystem.position, 'y', -500, 500, 1);
    // starsGui.add(this.particleSystem.position, 'z', -500, 500, 1);
    // starsGui.open()

    // let starsGuiRotate = this.GuiInit.addFolder("stars rotation");
    // starsGuiRotate.add(this.guiData, "autoRotate").name('自动旋转');
    // starsGuiRotate.add(this.particleSystem.rotation, 'x', -3.14, 3.14, 0.01);
    // starsGuiRotate.add(this.particleSystem.rotation, 'y', -3.14, 3.14, 0.01);
    // starsGuiRotate.add(this.particleSystem.rotation, 'z', -3.14, 3.14, 0.01);
    // //rotation是欧拉类型的值，单位是π；比如让物体按Y轴正方向旋转45°可以写成 object3D.rotation.y+=0.25*Math.PI
    // starsGuiRotate.open()

    // let otherGui = this.GuiInit.addFolder("其他");
    // otherGui.add(this.guiData, 'positionYBase', 20, 100, 1).name('晃动幅度');
    // otherGui.open()
  };
  private initStats = () => {
    this.stats = new Stats();
    this.stats.showPanel(0); // 0: fps, 1: ms, 2: mb, 3+: custom
    this.stats.dom.style.position = 'absolute';
    this.container.appendChild(this.stats.dom);
  };

  public toggleGui = (state: any = null) => {
    if (!this.GuiInit || !this.GuiInit.domElement) {
      return;
    }
    let display = this.GuiInit.domElement.style.display == 'none' ? '' : 'none';
    if (state == 0) {
      display = 'none';
    }
    this.GuiInit.domElement.style.display = display;
  };

  private initEventListen = () => {
    this.container.addEventListener('pointermove', this.onPointerMove);
  };
  private onPointerMove = (event) => {
    if (event.isPrimary === false) return;
    this.mouseData.mouseX = event.clientX - this.container.clientWidth;
    this.mouseData.mouseY = event.clientY - this.container.clientHeight;
  };

  private addLight = () => {
    let light = new Three.DirectionalLight(0xffffff);
    light.position.set(0, 200, 0);
    this.scene.add(light);
  };

  private addThings = () => {
    // const axesHelper = new Three.AxesHelper( 800 );
    // this.scene.add( axesHelper )  //添加坐标轴；红线是X轴，绿线是Y轴，蓝线是Z轴

    var obj1: any, obj2: any, loaded: boolean;
    this.loader.load('../../static/teapot-claraio.json', (obj) => {
      console.log('teapot-claraio', obj);
      // obj.applyMatrix4(new Three.Matrix4().makeTranslation(0, -10, 0));
      obj1 = obj;
      if (obj1 && obj2 && !loaded) {
        loaded = true;
        this.addPartice(obj1, obj2);
      }
    });
    this.loader.load('../../static/head-edited.json', (obj) => {
      console.log('head-edited', obj);
      // obj.applyMatrix4(new Three.Matrix4().makeTranslation(0, 10, 0));
      obj2 = obj;
      if (obj1 && obj2 && !loaded) {
        loaded = true;
        this.addPartice(obj1, obj2);
      }
    });

    /** 粒子 **/

    // this.initTween()
  };

  private addPartice = (obj1, obj2) => {
    console.log('???', obj1, obj2);
    var moreObj, lessObj;
    if (
      obj1.geometry.attributes.position.array.length >
      obj2.geometry.attributes.position.array.length
    ) {
      moreObj = obj1;
      lessObj = obj2;
    } else {
      moreObj = obj2;
      lessObj = obj1;
    }
    var position1: any[] = [];
    var position2: any[] = [];
    var moreLen = moreObj.geometry.attributes.position.array.length;
    var lessLen = lessObj.geometry.attributes.position.array.length;

    position1 = [...moreObj.geometry.attributes.position.array];
    position2 = [...lessObj.geometry.attributes.position.array];

    for (var i = lessLen, j = 0; i < moreLen; i++, j++) {
      position2.push(position2[j]); //要把少的补成跟多的一样的长度
    }

    // console.log('position1??', position1, position2)

    this.particleSystem = new Three.Group();
    var texture = new Three.TextureLoader().load('../../dot.png');
    this.Geometrys.starsGeometry = new Three.BufferGeometry();
    // for(let i = 0; i < moreLen; i++) {
    //   var pos = position1[i];
    //   // geometry.vertices.push(new Three.Vector3());
    //   // var color = new Three.Color();
    //   // color.r = pos.x/30;
    //   // color.g = pos.y/30;
    //   // color.b = pos.z/30;
    //   var material = new Three.PointsMaterial({color: '#ffffff', size:Math.random()*4+2, map:texture, blending:Three.AddEquation, depthTest: false, transparent:true});
    //   var particle = new Three.Points( this.Geometrys.starsGeometry, material );
    //   particle.position.copy(pos);
    //   particleSystem.add(particle);

    // }
    this.Geometrys.starsGeometry.setAttribute(
      'position',
      new Three.Float32BufferAttribute(position1, 3),
    );
    var material = new Three.PointsMaterial({
      color: 0x00ff00,
      size: 2,
      map: texture,
      blending: Three.CustomBlending,
      depthTest: false,
      transparent: true,
    });
    var particle = new Three.Points(this.Geometrys.starsGeometry, material);
    this.particleSystem.add(particle);

    var pos: any = { val: 1 };
    this.tween = new TWEEN.Tween(pos)
      .to({ val: 0 }, 2000)
      .easing(TWEEN.Easing.Quadratic.InOut)
      .delay(1000)
      .onUpdate(callback);
    let tweenBack = new TWEEN.Tween(pos)
      .to({ val: 1 }, 2000)
      .easing(TWEEN.Easing.Quadratic.InOut)
      .delay(1000)
      .onUpdate(callback);
    this.tween.chain(tweenBack);
    tweenBack.chain(this.tween);
    this.tween.start();

    // p = position1;
    let that = this;
    function callback(res) {
      // console.log('ressss', res)
      var val = res.val;

      let positionAnimate: any[] = [];
      for (let i = 0; i < position1.length; i++) {
        const po = position1[i] * val + position2[i] * (1 - val);
        positionAnimate.push(po);
      }
      that.Geometrys.starsGeometry.setAttribute(
        'position',
        new Three.Float32BufferAttribute(positionAnimate, 3),
      );

      // var particles = that.particleSystem.children;
      // for(var i = 0; i < particles.length; i++) {
      //   var particle = particles[i];
      //   var pos = particle.position;
      //   var material = particle.material;
      //   pos.x = position1[i].x * val + position2[i].x * (1-val);
      //   pos.y = position1[i].y * val + position2[i].y * (1-val);
      //   pos.z = position1[i].z * val + position2[i].z * (1-val);
      //   material.color.r = pos.z/20;
      //   material.color.g = pos.y/20;
      //   material.color.b = pos.z/20;
      // }
    }

    this.scene.add(this.particleSystem);
  };

  private initTween = () => {
    // cameray: 20, z: 500
    // var tween = new TWEEN.Tween(this.particleSystem.position).to({y: 12, z: 300}, 1000).start()
    // tween.easing(TWEEN.Easing.Circular.Out);
  };

  private animate = () => {
    // if(!this.renderer){return;}
    if (this.stats) {
      this.stats.begin();
    }

    this.render();
    TWEEN.update();

    if (this.stats) {
      this.stats.end();
    }
    this.animateFrame = requestAnimationFrame(this.animate);
  };

  private render = () => {
    // this.renderer.setClearColor(this.guiData.color,1.0);
    if (this.guiData.autoRotate && this.particleSystem) {
      // this.particleSystem.rotation.x+= 0.025
      this.particleSystem.rotation.y += 0.005;
    }

    if (this.guiData.mouseMove) {
      this.camera.position.x +=
        (-this.mouseData.mouseX - this.camera.position.x) * 0.015;
      this.camera.position.y +=
        (-this.mouseData.mouseY - this.camera.position.y) * 0.015;
    }

    this.renderer.render(this.scene, this.camera);
  };
}

const webGlControl = new WebGlControl();
export default webGlControl;
